import detailForm from "../detail.vue";
import {message} from "@/utils/message";
import {transformI18n} from "@/plugins/i18n";
import {addDialog} from "@/components/ReDialog";
import { ElMessage, ElMessageBox } from 'element-plus'
import type {FormItemProps} from "../utils/types";
import type {PaginationProps} from "@pureadmin/table";
import {getKeyList, deviceDetection} from "@pureadmin/utils";
import {applyController, getSalesList} from "@/api/crm";
import {type Ref, reactive, ref, onMounted, h, toRaw,createVNode} from "vue";
import {addDrawer} from "@/components/ReDrawer/index";
import orderDetailForm from "@/views/orders/all_list/form/orderDetail.vue";

export function useAccount(tableRef: Ref) {
  const form = reactive({
    name: "",
    code: "",
    audit_status: "3",
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const statusList = ref([]);
  const selectedNum = ref(0);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const salesman_arr = ref([]);


  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,pageSizes: [20, 40, 60,100,300,500],
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    { label: "勾选列", type: "selection", fixed: "left",width: 50,},
    { label: "id", prop: "id", width: 80, align: "left"},
    {label: "首次访问时间", prop: "visit_time",width:150,showOverflowTooltip:true,},
    { label: "图片", prop: "picture",width: 80,
      cellRenderer: scope => (
        <el-image style="width: 40px; height: 40px" src={scope.row.picture[0]} preview-src-list={[scope.row.picture]} preview-teleported={true} />
      ),
    },

    { label: "邮箱", prop: "email",align:'left', width: 180,sortable: "custom"},
    {label: "业务员", prop: "saleman", width: 80},
    {label: "创建用户", prop: "creator", width: 70},
    {label: "申请时间", prop: "created_at", width: 140},
    {label: "审核人", prop: "audit_id", width: 70},
    {label: "审核时间", prop: "audit_at", width: 140},
    {label: "审核状态", prop: "audit_status", width: 70}, //1同意，2驳回，3待审',
    {label: "备注", prop: "remark", minWidth: 150,showOverflowTooltip:true},
    {label: "操作", fixed: true, width: 170, slot: "operation"}
  ];


  function seeOrderDetail(e){
    let orderId = e.target.getAttribute('data-id')
    let row1 = ref({})
    row1.value = dataList.value.find(x=>x.order_id == orderId).orderinfo
    addDrawer({
      size: '60%',
      title: `订单详情:${orderId}`,
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      hideFooter: true,
      headerStyle:`{ marginBottom: '0px' }`,
      contentRenderer: () =>
        createVNode(orderDetailForm, {
          formInline: row1.value
        })
    });
  }
  function handleDelete(row) {
    applyController(row, "delete").then(res => chores(row, res, '删除', onSearch))
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }
  const getSalemanList = async function (page=1,limit=1000) {
    const {data} = await getSalesList({page,limit}); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    salesman_arr.value = data?.data;
  }
  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    form.page = pagination.currentPage
    form.limit = pagination.pageSize
    const {data} = await applyController(toRaw(form), 'get');
    dataList.value = data.data;
    statusList.value = data.status_arr;
    searchCondList.value = data?.search_cond_arr;
    pagination.total = data.total;
    pagination.pageSize = data.per_page;
    pagination.currentPage = data.current_page;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function chores(curData, res, title, done) {
    if (res.code === 0) {
      message(`您${title}了邮箱为${curData.email}的这条数据`, {type: "success"});
      done(); // 关闭弹框
      onSearch(); // 刷新表格数据
    } else {
      message(`${title}失败，原因：${res.message}`, { type: "error"});
    }
  }



  function openDialog(title = "新增", row?: FormItemProps){
    addDialog({
      title: `实物尺寸`,
      props: {
        formInline: JSON.parse(JSON.stringify(row || {title: title})),
      },
      width: "45%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      hideFooter: title != "新增",
      closeOnClickModal: false,
      contentRenderer: () => h(detailForm, {ref: formRef, formInline: null}),
      beforeSure: (done, {options}) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        FormRef.validate(valid => {
          if (valid) {
            applyController(curData, "put").then(res => chores(curData, res, title, done))
          }
        });
      }
    });
  }


  const exportExcel = async () => {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const { data } = await applyController(toRaw({page:1,export:1,limit:10000,'id':getKeyList(curSelected, "id").join(',')}),'get');
    // downloadByUrl(data.url)
    window.open(data.url, '_blank')
  };

  /** 数据权限 可自行开发 */
  const searchCondList =  ref([])

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    console.log(3333,selectedNum.value,val,getKeyList(curSelected, "id"))
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }
  const isEmpty = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;
  /** 批量操作 */
  function onbatchAct(field,row={}) {
    // 返回当前选中的行
    let curSelected = tableRef.value.getTableRef().getSelectionRows();
    if(!isEmpty(row)&&getKeyList(curSelected, "id").length==0){
      curSelected = [row]
    }
    const params1 = reactive({
      'id':getKeyList(curSelected, "id").join(','),
      'selected':curSelected,
      'field':field,
      'audit_result':'',
      'audit_remark':'',
    })
    if(getKeyList(curSelected, "id").length==0){
      return message(`未选中订单`, { type: "error"});
    }
    const formRules = reactive({
      audit_status: [{ required: true, message: "审核状态必填", trigger: "blur" }],
    });
    addDialog({
      width: "30%",
      title: "客户邮箱审核",
      contentRenderer: ({ index }) => (
        <el-form size="small" rules={formRules} model={params1} ref={formRef}>
          <el-form-item label="客户Id">
            {curSelected.map(item => (
              <el-tag  style="margin:2px 3px">{item.email}</el-tag>
            ))}
          </el-form-item>
          <el-form-item label="审核结果" prop="audit_status">
            <el-radio-group v-model={params1.audit_status}>
              <el-radio value={1} >同意</el-radio>
              <el-radio value={2} >驳回</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注信息">
            <el-input v-model={params1.remark} rows="10" type="textarea" placeholder="备注信息"/>
          </el-form-item>
        </el-form>
      ),
      beforeSure: async(done, { options }) => {
        await formRef.value?.validate(valid => {
          if (valid) {
            applyController(params1,"put").then(res=>{
              if (res.code != 0) {
                message(res.message, { type: "error"});
                return; // 终止链式调用
              }
              if (Array.isArray(res.data) && res.data.length === 0) {
                message(params1.audit_status==1?`成功修改审核状态`:'你已驳回这条审核记录', { type: "success" });
                done();
                tableRef.value.getTableRef().clearSelection();
                onSearch();
                return;
              }
              // 2. 弹出确认框
              return ElMessageBox.confirm('此用户已经引流给了用户'+res.data.saleman_id+'，继续操作将强制将客户和订单变更为新用户，是否继续?', 'Warning',
                { confirmButtonText: 'OK', cancelButtonText: 'Cancel', type: 'warning'}
              ).then(() => {
                params1.force =1;
                return applyController(params1, "put");
                }).then(newRes => {
                  // 4. 处理强制请求的响应
                  if (newRes.code == 0) {
                    message(`强制引流成功`, { type: "success" });
                    done();
                    tableRef.value.getTableRef().clearSelection();
                    onSearch();
                    return;
                  } else {
                    message(newRes.message, { type: "error" });
                  }
                }).catch(err => {
                  if (err !== 'cancel') {
                    message("操作失败: " + err.message, { type: "error" });
                  }
                });

            })
          }
        });
      },
    });
  }

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
    getSalemanList();
  });


  return {
    form, isShow, curRow, loading, columns, dataList, isLinkage, pagination, isExpandAll, isSelectAll,exportExcel,
    selectedNum,onSelectionCancel,handleSelectionChange,onbatchAct,
    statusList,salesman_arr,
    onSearch, resetForm,
    openDialog,searchCondList,
    handleDelete, filterMethod, transformI18n, handleSizeChange,
    handleCurrentChange
  };
}
